import React from 'react';
import { Tooltip } from 'antd';
import { useRequest, useAntdTable } from '@/hooks';
import request from '@/utils/request';
import cmdbres from '@/data/cmdbres';

const UNIQ_CHECK_RESULT = `UNIQ_CHECK_RESULT_${Date.now()}`;

/**
 * 资源分类标签
 */
export function useResourceCategoryTabs(options) {
    return useRequest(async (id) => {
        const [{ data: resourceCategory }, { data: resourceStatistics }] = await Promise.all([
            request({ ...cmdbres.queryOssImportTaskModels(id) }),
            request({ ...cmdbres.queryOssImportTaskModelStat(id) }),
        ]);

        const resourceStatisticsMap = resourceStatistics.reduce(
            (prev, { cmModuleId, total }) => ({ ...prev, [cmModuleId]: total }),
            {}
        );

        return resourceCategory.map(({ moduleName, cmModuleId }) => ({
            label: `${moduleName}(${resourceStatisticsMap[cmModuleId]})`,
            key: cmModuleId,
        }));
    }, options);
}

/**
 * 资源列表表头
 */
export const useResourceColumns = (cmModuleId) => {
    return useRequest(async () => {
        const { data } = await request({ ...cmdbres.queryOssImportTaskModelFields(cmModuleId) });

        const renderCell = (record) => {
            if (!record) return '-';

            const { value, errors } = record;
            const text = value || '-'

            if (errors.length) {
                return (
                    <Tooltip
                        title={
                            <div style={{ color: '#D9001B' }}>
                                {errors.map((error, index) => (
                                    <div key={index}>{error}</div>
                                ))}
                            </div>
                        }
                    >
                        <span style={{ color: '#D9001B', cursor: 'pointer' }}>{text}</span>
                    </Tooltip>
                );
            }

            return text;
        };

        return [
            ...data.map(({ propertyName, propertyKey }) => ({
                title: propertyName,
                dataIndex: propertyKey,
                render: renderCell,
            })),
            {
                title: '唯一校验结果',
                dataIndex: UNIQ_CHECK_RESULT,
                render(record) {
                    return renderCell(record && { ...record, value: record.errors.length ? '未通过' : '通过' });
                },
            },
        ];
    });
};

/**
 * 资源列表
 */
export const useResourceList = (ossFileUploadTaskId, cmModuleId) => {
    return useAntdTable(async (tableData) => {
        const { current, pageSize } = tableData;

        const { total, data } = await request({
            ...cmdbres.queryOssImportTaskModelDataList(ossFileUploadTaskId),
            data: {
                pageNumber: current,
                pageSize,
                queryFilter: {
                    EQ: {
                        ossFileUploadTaskId,
                        cmModuleId,
                    },
                },
            },
        });

        return {
            list: data.map((item) => {
                return item.reduce((prev, { checkType, propertyKey, propertyValue, verificationRulesMessage }) => {
                    const key = checkType === 'property' ? propertyKey : UNIQ_CHECK_RESULT;
                    const errors = verificationRulesMessage ? [verificationRulesMessage] : [];

                    if (prev[key]) {
                        prev[key]['errors'].push(...errors);
                        return prev;
                    }

                    return {
                        ...prev,
                        [key]: { value: propertyValue, errors },
                    };
                }, {});
            }),
            total,
        };
    });
};
